package com.alipay.rebate.shop.aspect;

import com.alipay.rebate.shop.checker.ParameterChecker;
import com.alipay.rebate.shop.pojo.common.CommonPageRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class CheckPageRequestAspect {

  private Logger logger = LoggerFactory.getLogger(CheckPageRequestAspect.class);

  @Autowired
  ParameterChecker parameterChecker;

  @Pointcut("execution(public * com.alipay.rebate.shop.controller.*.*.*(..))")
  public void setPageNoAndSize(){

  }

  @Before("setPageNoAndSize()")
  public void beforeEndPoint(JoinPoint joinPoint) {

    Object[] args = joinPoint.getArgs();
    logger.debug("check page request");
    if (args != null && args.length > 0) {
      for(int i =0; i<args.length; i++){
        Object obj = args[i];
        if(obj instanceof CommonPageRequest){
          logger.debug("before check page request is:{}",obj);
          CommonPageRequest pageRequest = (CommonPageRequest) obj;
          pageRequest.setPageNo(parameterChecker.checkAndGetPageNo(pageRequest.getPageNo()));
          pageRequest.setPageSize(parameterChecker.checkAndGetPageSize(pageRequest.getPageSize()));
          logger.debug("after check page request :{}",obj);
        }
      }
    }
  }

}
